import { login } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import md5 from 'md5'
import { Message } from 'element-ui'

const arrRoles = [
  { RightNo: '1000', RightName: '基础信息' },
  { RightNo: '1001', RightName: '公司' },
  { RightNo: '1002', RightName: '营业点' },
  { RightNo: '1003', RightName: '区域信息' },
  { RightNo: '1004', RightName: '小区信息' },
  { RightNo: '1005', RightName: '客户信息' },
  { RightNo: '1006', RightName: '表计信息' },
  { RightNo: '1007', RightName: '表参数配置' },
  { RightNo: '1008', RightName: '账册信息' },
  { RightNo: '1009', RightName: '价格信息' },
  { RightNo: '1009', RightName: '强制删除资料' },

  { RightNo: '2000', RightName: '系统管理' },
  { RightNo: '2001', RightName: '部门管理' },
  { RightNo: '2002', RightName: '操作员管理' },
  { RightNo: '2003', RightName: '角色管理' },
  { RightNo: '2004', RightName: '设置参数' },
  { RightNo: '2005', RightName: '操作日志' },

  { RightNo: '3000', RightName: '数据报表' },
  { RightNo: '3001', RightName: '充值记录' },
  { RightNo: '3002', RightName: '预储值记录' },
  { RightNo: '3003', RightName: '收费记录' },
  { RightNo: '3004', RightName: '调价记录' },
  { RightNo: '3005', RightName: '审核记录' },
  { RightNo: '3007', RightName: '强制设置充值状态和充值次数' },

  { RightNo: '4000', RightName: '数据监控' },
  { RightNo: '4001', RightName: '实时数据' },
  { RightNo: '4002', RightName: '历史数据' },
  { RightNo: '4003', RightName: '每日用量' },
  { RightNo: '4004', RightName: '每月用量' },
  { RightNo: '4005', RightName: '每日用量汇总' },
  { RightNo: '4006', RightName: '每月用量汇总' },
  { RightNo: '4007', RightName: '曲线分析' },
  { RightNo: '4008', RightName: '报警设置' },
  { RightNo: '4009', RightName: '报警确认' },
  { RightNo: '4010', RightName: '余额报警提醒' },

  { RightNo: '5000', RightName: '业务管理' },
  { RightNo: '5001', RightName: '开户' },
  { RightNo: '5002', RightName: '远程充值' },
  { RightNo: '5003', RightName: '远程命令' },
  { RightNo: '5004', RightName: '气价管理' },
  // { RightNo: '5005', RightName: '结算' },
  { RightNo: '5006', RightName: '打印单据' },
  { RightNo: '5007', RightName: '预储值' },
  { RightNo: '5008', RightName: 'IC卡业务' },

  { RightNo: '6000', RightName: '审核操作' },
  { RightNo: '6001', RightName: '通过' },
  { RightNo: '6002', RightName: '拒绝' },
  { RightNo: '6003', RightName: '撤回' },

  { RightNo: '7000', RightName: '抄表管理' },
  { RightNo: '7001', RightName: '抄表设置' },
  { RightNo: '7002', RightName: '抄表结算' },
  { RightNo: '7003', RightName: '结算记录' },
  { RightNo: '7004', RightName: '批量抄表结算' },

  { RightNo: '8000', RightName: '工艺图管理' },
]

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, Target} = userInfo
    return new Promise((resolve, reject) => {
      login({ loginName: username.trim(), password: md5(password), VerifyCode: Target }).then(res => {
        if (res !== undefined) {
          if (res.Data === false) {
            return
          }
          
          // localStorage.setItem('RoleRights', JSON.stringify(arrRoles))
          const data = res.Data
          localStorage.setItem('RoleId', JSON.stringify(data.RoleId))
          localStorage.setItem('OperatorId', JSON.stringify(data.OperatorId))
          // 存储权限
          if (data.SuperAdmin === true) {
            let arr = []
            arrRoles.map(item => {
              arr.push(item.RightNo)
            })
            localStorage.setItem('RoleRights', JSON.stringify(arr))
          }
          if (data.SuperAdmin === false && data.RoleRights !== '[]') {
            localStorage.setItem('RoleRights', JSON.stringify(data.RoleRights))  
          }
          if (data.SuperAdmin !== true && data.RoleRights === '[]') {
            Message({
              message: '当前账号没有权限',
              type: 'error',
              duration: 5 * 1000
            })
            throw new Error('没有权限!')
            return
          }
        }
        const Data = res.Data
        commit('SET_TOKEN', Data.Token)
        setToken(Data.Token)
        commit('SET_TOKEN', [Data.LoginName])
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    if (localStorage.getItem('RoleRights') == ['']) {
      return
    }
    let RoleRights = JSON.parse(localStorage.getItem('RoleRights'))
    let newRoles = []
 
    for (let i = 0; i < RoleRights.length; i++) {
      for (let j = 0;j < arrRoles.length; j++) {
        if (RoleRights[i] == arrRoles[j].RightNo) {
          newRoles.push(arrRoles[j].RightName)
        }
      }
    }
    return new Promise((resolve, reject) => {
      commit('SET_ROLES', newRoles)
      resolve({
        roles: newRoles
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resetRouter()
      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch('tagsView/delAllViews', null, { root: true })
      resolve()
      // .catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  // async changeRoles({ commit, dispatch }, role) {
  //   const token = role + '-token'

  //   commit('SET_TOKEN', token)
  //   setToken(token)

  //   const { roles } = await dispatch('getInfo')

  //   resetRouter()

  //   // generate accessible routes map based on roles
  //   const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
  //   // dynamically add accessible routes
  //   router.addRoutes(accessRoutes)

  //   // reset visited views and cached views
  //   dispatch('tagsView/delAllViews', null, { root: true })
  // }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
